//
//  CYSudokuModifyViewController.m
//  cyjf
//
//  Created by tauCross on 2017/8/24.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYSudokuModifyViewController.h"

#import "CYMainController.h"

#import <AVFoundation/AVFoundation.h>



@interface CYSudokuModifyViewController ()

@property(nonatomic, strong)NSMutableArray<UIButton *> *points;
@property(nonatomic, strong)NSMutableArray<UIButton *> *choosePoints;
@property(nonatomic, strong)NSMutableArray<UIButton *> *thumbPoints;
@property(nonatomic, strong)UILabel *hintLabel;
@property(nonatomic, strong)UIImageView *lineImageView;
@property(nonatomic, assign)BOOL drawing;

@property(nonatomic, strong)NSString *password;
@property(nonatomic, assign)NSInteger retryCount;
@property(nonatomic, assign)BOOL verified;

@property(nonatomic, strong)UIButton *actionResetButton;
@property(nonatomic, strong)UIButton *actionForgotButton;

@end


@implementation CYSudokuModifyViewController

- (void)loadData
{
    self.retryCount = 0;
    self.password = nil;
    self.verified = NO;
}

- (void)loadUI
{
    self.tableView.hidden = YES;
    self.contentView.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"修改手势密码";
    
    self.lineImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.lineImageView];

    self.hintLabel = [[UILabel alloc] init];
    self.hintLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    self.hintLabel.textAlignment = NSTextAlignmentCenter;
    self.hintLabel.textColor = HEXCOLOR(@"999999");
    self.hintLabel.text = @"请绘制原手势密码";
    [self.contentView addSubview:self.hintLabel];
    
    [self createPoints];
    for(UIButton *button in self.thumbPoints)
    {
        button.hidden = YES;
    }
    
    self.actionResetButton = [[UIButton alloc] init];
    [self.actionResetButton setTitle:@"重新绘制图案" forState:UIControlStateNormal];
    self.actionResetButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    [self.actionResetButton setTitleColor:HEXCOLOR(@"999999") forState:UIControlStateNormal];
    [self.actionResetButton addTarget:self action:@selector(onActionResetButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.actionResetButton];
    self.actionResetButton.hidden = YES;
    
    self.actionForgotButton = [[UIButton alloc] init];
    [self.actionForgotButton setTitle:@"忘记手势密码" forState:UIControlStateNormal];
    self.actionForgotButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    [self.actionForgotButton setTitleColor:HEXCOLOR(@"999999") forState:UIControlStateNormal];
    [self.actionForgotButton addTarget:self action:@selector(onActionForgotButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.actionForgotButton];
}

- (void)layoutUI
{
    self.lineImageView.frame = self.contentView.bounds;
    
    self.actionResetButton.width = 100;
    self.actionResetButton.height = 44;
    self.actionResetButton.centerX = self.contentView.width / 2;
    self.actionResetButton.bottom = self.contentView.height - 19;
    
    self.actionForgotButton.frame = self.actionResetButton.frame;
    
    self.hintLabel.height = 20;
    self.hintLabel.width = self.contentView.width;
    self.hintLabel.left = 0;
    self.hintLabel.centerY = 110;
    
    {
        CGFloat startX = self.contentView.width / 2 - 120;
        CGFloat x = startX;
        CGFloat y = 150;
        CGFloat startX_t = self.contentView.width / 2 - 20;
        CGFloat x_t = startX_t;
        CGFloat y_t = 30;
        for(NSInteger i = 0; i < 9; i ++)
        {
            UIButton *button = self.points[i];
            button.x = x;
            button.y = y;
            button = self.thumbPoints[i];
            button.x = x_t;
            button.y = y_t;
            if((i + 1) % 3)
            {
                x += 90;
                x_t += 15;
            }
            else
            {
                x = startX;
                x_t = startX_t;
                y += 90;
                y_t += 15;
            }
        }
    }
}

#pragma mark - Private Method
- (BOOL)checkValid
{
    @weakify(self);
    BOOL flag;
    dispatch_block_t block;
    if(self.verified)
    {
        if(self.password)
        {
            if([self.password isEqualToString:[self sudokuPassword]])
            {
                flag = YES;
                
                self.hintLabel.text = @"手势密码修改成功";
                self.hintLabel.textColor = APP_DEFAULT_COLOR_BLUE;
                [CYSudokuManager saveSudokuPassword:self.password];
                [SVProgressHUD showSuccessWithStatus:@"手势密码修改成功"];
                APP_LOCK_USER_INTERACTION;
                block = dispatch_block_create(0, ^{
                    APP_UNLOCK_USER_INTERACTION;
                    @strongify(self);
                    [SVProgressHUD dismiss];
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            else
            {
                flag = NO;
                
                self.retryCount ++;
                if(self.retryCount < 5)
                {
                    self.hintLabel.text = @"两次绘制图案不一致，请重新绘制";
                    self.hintLabel.textColor = APP_DEFAULT_COLOR_RED;
                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                    APP_LOCK_USER_INTERACTION;
                    block = dispatch_block_create(0, ^{
                        @strongify(self);
                        APP_UNLOCK_USER_INTERACTION;
                        [self.choosePoints removeAllObjects];
                        self.lineImageView.image = nil;
                        [self updatePointsWithValid:YES];
                        [self updateThumbPoints];
                    });
                }
                else
                {
                    self.hintLabel.text = @"手势密码已清空，请重新绘制";
                    self.hintLabel.textColor = APP_DEFAULT_COLOR_RED;
                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                    self.password = nil;
                    self.actionResetButton.hidden = YES;
                    APP_LOCK_USER_INTERACTION;
                    block = dispatch_block_create(0, ^{
                        @strongify(self);
                        APP_UNLOCK_USER_INTERACTION;
                        [self.choosePoints removeAllObjects];
                        self.lineImageView.image = nil;
                        [self updatePointsWithValid:YES];
                        [self updateThumbPoints];
                    });
                    
                }
            }
        }
        else
        {
            if(self.choosePoints.count < 4)
            {
                flag = NO;
                
                self.hintLabel.text = @"请至少连接4个点";
                self.hintLabel.textColor = APP_DEFAULT_COLOR_RED;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                APP_LOCK_USER_INTERACTION;
                block = dispatch_block_create(0, ^{
                    @strongify(self);
                    APP_UNLOCK_USER_INTERACTION;
                    [self.choosePoints removeAllObjects];
                    self.lineImageView.image = nil;
                    [self updatePointsWithValid:YES];
                    [self updateThumbPoints];
                });
            }
            else
            {
                flag = YES;
                
                self.password = [self sudokuPassword];
                self.retryCount = 0;
                self.hintLabel.text = @"请再一次绘制解锁图案";
                self.hintLabel.textColor = HEXCOLOR(@"999999");
                self.actionResetButton.hidden = NO;
                APP_LOCK_USER_INTERACTION;
                block = dispatch_block_create(0, ^{
                    @strongify(self);
                    APP_UNLOCK_USER_INTERACTION;
                    [self.choosePoints removeAllObjects];
                    self.lineImageView.image = nil;
                    [self updatePointsWithValid:YES];
                    [self updateThumbPoints];
                });
            }
        }
    }
    else
    {
        NSString *password = [CYSudokuManager sudokuPassword];
        if([password isKindOfClass:[NSString class]] && ![password isEqualToString:[self sudokuPassword]])
        {
            flag = NO;
            
            self.retryCount ++;
            if(self.retryCount < 5)
            {
                self.hintLabel.text = [NSString stringWithFormat:@"密码输入错误，您还可以输入%li次", (long)(5 - self.retryCount)];
                self.hintLabel.textColor = APP_DEFAULT_COLOR_RED;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                APP_LOCK_USER_INTERACTION;
                block = dispatch_block_create(0, ^{
                    @strongify(self);
                    APP_UNLOCK_USER_INTERACTION;
                    [self.choosePoints removeAllObjects];
                    self.lineImageView.image = nil;
                    [self updatePointsWithValid:YES];
                });
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:@"请重新登录"];
                block = dispatch_block_create(0, ^{
                    CYStandardAuthManager.currentAuth = nil;
                    [CYStandardAuthManager saveAuth];
                    [[CYMainController standardController] goHome];
                    [[CYMainController standardController] showLogIn];
                });
            }
        }
        else
        {
            flag = YES;
            
            self.verified = YES;
            self.hintLabel.textColor = HEXCOLOR(@"999999");
            self.hintLabel.text = @"请绘制新解锁图案";
            for(UIButton *button in self.thumbPoints)
            {
                button.hidden = NO;
            }
            self.actionForgotButton.hidden = YES;
            APP_LOCK_USER_INTERACTION;
            block = dispatch_block_create(0, ^{
                APP_UNLOCK_USER_INTERACTION;
                @strongify(self);
                [self.choosePoints removeAllObjects];
                self.lineImageView.image = nil;
                [self updatePointsWithValid:YES];
            });
        }
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
    return flag;
}

- (NSString *)sudokuPassword
{
    NSMutableString *password = [[NSMutableString alloc] init];
    for(UIButton *button in self.choosePoints)
    {
        [password appendString:@(button.tag).stringValue];
    }
    return password;
}

- (UIButton *)pointButtonWithTag:(NSInteger)tag
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    button.userInteractionEnabled = NO;
    button.tag = tag;
    [button setImage:CYImage(@"sudoku_normal") forState:UIControlStateNormal];
    [button setImage:CYImage(@"sudoku_choose") forState:UIControlStateSelected];
    [button setImage:CYImage(@"sudoku_error") forState:UIControlStateDisabled];
    return button;
}

- (UIButton *)thumbPointButtonWithTag:(NSInteger)tag
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    button.userInteractionEnabled = NO;
    button.tag = tag;
    [button setImage:CYImage(@"sudoku_thumb_normal") forState:UIControlStateNormal];
    [button setImage:CYImage(@"sudoku_thumb_choose") forState:UIControlStateSelected];
    return button;
}

- (void)createPoints
{
    self.points = [NSMutableArray array];
    self.choosePoints = [NSMutableArray array];
    self.thumbPoints = [NSMutableArray array];
    for(NSInteger i = 0; i < 9; i++)
    {
        UIButton *button = [self pointButtonWithTag:i];
        [self.points addObject:button];
        [self.contentView addSubview:button];
        
        button = [self thumbPointButtonWithTag:i];
        [self.thumbPoints addObject:button];
        [self.contentView addSubview:button];
    }
}

#pragma mark - Control Events
- (void)onActionResetButtonTouchUpInside
{
    self.hintLabel.text = @"手势密码已清空，请重新绘制";
    self.hintLabel.textColor = APP_DEFAULT_COLOR_RED;
    self.password = nil;
    self.actionResetButton.hidden = YES;
    [self.choosePoints removeAllObjects];
    self.lineImageView.image = nil;
    [self updatePointsWithValid:YES];
    [self updateThumbPoints];
}

- (void)onActionForgotButtonTouchUpInside
{
    @weakify(self);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入车蚁金服登录密码"
                                                                             message:[NSString stringWithFormat:@"（登录手机账号：%@）", CYStandardAuthManager.currentAuth.mobile.cy_maskPhoneNumber]
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.secureTextEntry = YES;
        textField.returnKeyType = UIReturnKeySend;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    @weakify(alertController);
    [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(alertController);
        @strongify(self);
        NSString *password = [alertController textFields].firstObject.text;
        if(password.length)
        {
            [SVProgressHUD show];
            [CYStandardDataAPI user_loginWithMobile:CYStandardAuthManager.currentAuth.mobile password:password complete:^(CYResponse *response) {
                dispatch_block_t block;
                if(response.code == 0)
                {
                    [SVProgressHUD dismiss];
                    self.verified = YES;
                    self.hintLabel.textColor = HEXCOLOR(@"999999");
                    self.hintLabel.text = @"请绘制新解锁图案";
                    for(UIButton *button in self.thumbPoints)
                    {
                        button.hidden = NO;
                    }
                    self.actionForgotButton.hidden = YES;
                    APP_LOCK_USER_INTERACTION;
                    block = dispatch_block_create(0, ^{
                        APP_UNLOCK_USER_INTERACTION;
                        @strongify(self);
                        [self.choosePoints removeAllObjects];
                        self.lineImageView.image = nil;
                        [self updatePointsWithValid:YES];
                    });
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:@"登录密码错误，请重新登录"];
                    APP_LOCK_USER_INTERACTION;
                    block = dispatch_block_create(0, ^{
                        APP_UNLOCK_USER_INTERACTION;
                        CYStandardAuthManager.currentAuth = nil;
                        [CYStandardAuthManager saveAuth];
                        [[CYMainController standardController] goHome];
                        [[CYMainController standardController] showLogIn];
                    });
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"请输入密码"];
            [self onActionForgotButtonTouchUpInside];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - Draw
- (void)updateSudokuWithPoint:(CGPoint)point;
{
    [self updatePointsWithValid:YES];
    [self updateThumbPoints];
    [self drawLineWithPoint:[NSValue valueWithCGPoint:point] color:APP_DEFAULT_COLOR_BLUE];
}

- (void)endSudoku
{
    BOOL valid = [self checkValid];
    [self updatePointsWithValid:valid];
    [self updateThumbPoints];
    [self drawLineWithPoint:nil color:valid ? APP_DEFAULT_COLOR_BLUE : APP_DEFAULT_COLOR_RED];
}

- (void)updatePointsWithValid:(BOOL)valid
{
    for(UIButton *button in self.points)
    {
        if([self.choosePoints containsObject:button])
        {
            if(valid)
            {
                button.enabled = YES;
                button.selected = YES;
            }
            else
            {
                button.enabled = NO;
                button.selected = NO;
            }
        }
        else
        {
            button.enabled = YES;
            button.selected = NO;
        }
    }
}

- (void)updateThumbPoints
{
    for(UIButton *button in self.thumbPoints)
    {
        button.selected = NO;
    }
    for(UIButton *button in self.choosePoints)
    {
        for(UIButton *button_t in self.thumbPoints)
        {
            if(button.tag == button_t.tag)
            {
                button_t.selected = YES;
            }
        }
    }
}

- (void)drawLineWithPoint:(NSValue *)pointValue color:(UIColor *)color
{
    if(self.choosePoints.count == 0)
    {
        self.lineImageView.image = nil;
        return;
    }
    UIImage *image = nil;
    UIColor *lineColor = color;
    UIGraphicsBeginImageContextWithOptions(self.lineImageView.frame.size, NO, SCREEN_SCALE);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
    CGContextMoveToPoint(context, self.choosePoints.firstObject.centerX, self.choosePoints.firstObject.centerY);
    for(UIButton *button in self.choosePoints)
    {
        CGContextAddLineToPoint(context, button.centerX, button.centerY);
        CGContextMoveToPoint(context, button.centerX, button.centerY);
    }
    if(pointValue)
    {
        CGPoint point = [pointValue CGPointValue];
        CGContextAddLineToPoint(context, point.x, point.y);
    }
    CGContextStrokePath(context);
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.lineImageView.image = image;
}

#pragma mark - GestureRecognizer
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(self.drawing)
    {
        return;
    }
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.contentView];
    for(UIButton *button in self.points)
    {
        if(CGRectContainsPoint(button.frame, point))
        {
            self.drawing = YES;
            [self.choosePoints addObject:button];
            break;
        }
    }
    [self updateSudokuWithPoint:point];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(self.drawing)
    {
        UITouch *touch = touches.anyObject;
        CGPoint point = [touch locationInView:self.contentView];
        for(UIButton *button in self.points)
        {
            if(CGRectContainsPoint(button.frame, point) && ![self.choosePoints containsObject:button])
            {
                [self.choosePoints addObject:button];
                break;
            }
        }
        [self updateSudokuWithPoint:point];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(self.drawing)
    {
        [self endSudoku];
    }
    self.drawing = NO;
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

@end
